package org.hoyi.util;

import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;

import org.hoyi.DB.ctrl.Console;
import org.hoyi.loader.JarLoader;

/**
 * 文件处理.
 * @author sam
 *
 */
public class StreamUtils {
	
	public static StreamUtils Create() {
		return new StreamUtils();
	}
	/**
	 * 统一文件读取的方法.
	 * @param url
	 * @return
	 */
	public InputStream GotInputStream(String url) {
		try {
			InputStream _inputStream;
//			if (HoyiCloudApplication.DebugMode) { // 取消Debug模式，改成重启服务保持最新.。
//				_inputStream = this.getClass().getClassLoader().getResource(url).openStream();
//			} else {
				_inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(url);
//			}
			return _inputStream;
		} catch (Exception e) {
			return null;
		}
	}
	/**
	 * Resource资源包括target/classes, src/, jar包内等.
	 * @throws Exception 
	 */
	public byte[] ReaderResource(String url) throws Exception {
		try {
			InputStream ins = StreamUtils.Create().GotInputStream(url);
			byte[] bts = new ByteUtils().readStream(ins);
			return bts;
		} catch (Exception e) {
			if(JarLoader.resMap.containsKey(url)) {
				byte[] bts = JarLoader.resMap.get(url);
				return bts;
			}else {
				throw e;
			}
		}
	}
	
	/**
	 * 读取本地路径的文件.
	 * @param url	文件路径.
	 * @return
	 * @throws Exception
	 */
	public byte[] ReadLocalFileResource(String url) throws Exception {
		File _files = new File(url);
		byte[] bts = Files.readAllBytes(_files.toPath());
		return bts;
	}
	
}
